<template>
  <div v-loading="loading" class="app-container">
    <el-collapse v-model="activeName" accordion>
      <el-collapse-item name="1">
        <template slot="title">
          <i class="el-icon-search" />搜索栏
        </template>
        <div class="head-container">
          <el-form class="searchform" :model="params" :inline="true" size="mini" label-width="auto">
            <el-form-item label="流水号">
              <el-input v-model="params.vendorPortalId" size="mini" placeholder="输入流水号" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="条码">
              <el-input v-model="params.upcNbrs" size="mini" placeholder="多个条码以逗号分割" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="商品号">
              <el-input v-model="params.itemNbr" size="mini" placeholder="输入条码检验码/商品号搜索" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="部门">
              <el-input v-model="params.deptNbr" size="mini" placeholder="输入部门搜索" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="商品说明1">
              <el-input v-model="params.item1Desc" size="mini" placeholder="输入商品说明1模糊匹配" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="供应商之商品代码">
              <el-input v-model="params.vendorStockId" size="mini" placeholder="输入供应商之商品代码" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="供应商编号">
              <el-input v-model="params.vendorNbr" size="mini" placeholder="输入供应商编号" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="供应商名称">
              <el-input v-model="params.vendorName" size="mini" placeholder="输入供应商名称模糊匹配" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="params.itemStatus" size="mini" placeholder="选择搜索" clearable style="width: 200px">
                <el-option :key="0" label="供应商撤回" :value="0" />
                <el-option :key="1" label="供应商上传待审" :value="1" />
                <el-option :key="-2" label="已驳回至供应商" :value="-2" />
              </el-select>
            </el-form-item>
            <el-form-item label="上传时间">
              <el-date-picker
                v-model="syncTime"
                size="mini"
                type="datetimerange"
                value-format="yyyy/MM/dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="syncTimeChange"
              />
            </el-form-item>
            <el-form-item>
              <el-button size="mini" type="primary" style="float:right;margin-left:0px;" icon="el-icon-refresh" round @click="resetForm">重置</el-button>
              <el-button size="mini" type="primary" style="float:right;margin-left:0px;" icon="el-icon-search" round @click="toQuery">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div style="padding-top:5px">
      <el-button size="mini" type="danger" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-circle-close" round @click="batchReject">驳回</el-button>
      <el-button size="mini" type="success" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-circle-check" round @click="batchAgreeCoiFlag">同意</el-button>
      <!--<el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-edit" round @click="updateFineLineNbr">修改细分类号</el-button>-->
      <!-- <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;" icon="el-icon-connection" round @click="doBatchChangeBuyer">批量转交Item</el-button> -->
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-download" round @click="doExportExcel">导出Excel</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-edit" round @click="doClearSelection">取消选择</el-button>
      <el-table ref="itemTab" :data="data" :row-key="getRowKeys" stripe size="small" border style="width: 100%;" @header-dragend="colChange" @sort-change="sortChange" @selection-change="handleSelectionChange">
        <el-table-column :reserve-selection="true" type="selection" align="center" width="55" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="流水号" prop="vendorPortalId" :width="colWidths.vendorPortalId" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="条码" prop="upcNbr" :width="colWidths.upcNbr">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="toItemInfo(scope.row)">{{ scope.row.upcNbr }}</el-button>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="部门" prop="deptNbr" :width="colWidths.deptNbr" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="商品说明1" prop="item1Desc" :width="colWidths.item1Desc" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="供应商之商品代码" prop="vendorStockId" :width="colWidths.vendorStockId" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="供应商编号" prop="vendorNbr" :width="colWidths.vendorNbr" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="供应商名称" prop="vendorName" :width="colWidths.vendorName" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="单品未税成本" prop="vnpkCostAmtVnpkQty" :width="colWidths.vnpkCostAmtVnpkQty" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="进项税" prop="vatIn" :width="colWidths.vatIn" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="最近更新时间" prop="updatedTime" :width="colWidths.updatedTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updatedTime) }}</span>
          </template>
        </el-table-column>
        <itemStatusForm />
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <!--<el-button size="mini" type="warning" @click="updateOneFineLineNbr(scope.row)">修改FineLine</el-button>-->
            <el-button size="mini" type="warning" @click="toItemInfo(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page.sync="currentPage"
        :page-sizes="[10,50,100,500]"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </div>
    <itemForm ref="itemForm" :parent="parent" />
    <choice ref="choice" :parent="parent" />
  </div>
</template>

<script>
import itemForm from '@/views/new-item/info'
import choice from '@/views/new-item/choice/choice'
import initData from '@/utils/initData'
import { parseTime } from '@/utils/index'
import { Message } from 'element-ui'
import { batchFirstAuditAgree, batchFirstAuditReject, batchChangeBuyer } from '@/api/new-item'
import { toItemInfo } from '@/utils/newItem'
import itemStatusForm from '@/views/part/itemStatus'
import { doDownload } from '@/api/download'
import { selectApproval, approvalTask } from '@/api/reason/dataO2o'

export default {
  components: { itemForm, itemStatusForm, choice },
  mixins: [initData],
  data() {
    return {
      syncTime: [],
      parent: this,
      loading: false,
      ids: [],
      idsApproval: [],
      activeName: '1',
      rowsApproval: {},
      rows: {}
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    parseTime,
    toItemInfo,
    beforeInit() {
      this.url = '/new-item/firstAuditList'
      this.params.pageNum = this.page
      this.params.pageSize = this.size
      return true
    },
    // 上传时间日期组件触发
    syncTimeChange(val) {
      this.params.findSyncTimeStartDate = val[0]
      this.params.findSyncTimeEndDate = val[1]
    },
    // 列表排序触发
    sortChange(val) {
      let sortType = ''
      if (val.order === 'descending') {
        sortType = ' DESC'
      } else if (val.order === 'ascending') {
        sortType = ' ASC'
      }
      this.params.sort = val.prop + sortType
      this.init()
    },
    // 查询
    toQuery() {
      this.page = 0
      this.currentPage = 1
      if (this.params.upcNbrs) {
        this.params.upcNbrs = this.params.upcNbrs.trim().replaceAll('，', ',')
      }
      this.init()
      this.doClearSelection()
    },
    // 查询栏重置触发
    resetForm() {
      this.params = {}
      this.syncTime = []
    },
    // 列表多选框触发
    handleSelectionChange(val) {
      this.ids = []
      this.rows = []
      val.forEach(item => {
        this.ids.push(item.id)
        this.rows.push(item)
      })
    },
    // 翻页选择row的key值
    getRowKeys(row) {
      return row.id
    },
    async batchAgreeCoiFlag() {
      if (window.coiFlag) {
        const result = await approvalTask()
        console.log(result)
        this.rowsApproval = []
        console.log(this.rowsApproval)
        console.log(this.rowsApproval.length)
        this.url = '/approvalO2oController/selectApproval'
        await selectApproval(this.url, this.ids).then(res => {
          console.log('res----', res)
          console.log('res----', res.result)
          if (res.result != null) {
            res.result.forEach(item => {
              // eslint-disable-next-line eqeqeq
              if ((item.status == 2 && item.status1 == 1 && item.status2 == 1 && item.status3 == 1) || (item.status == 2 && item.status1 == null && item.status2 == null && item.status3 == null)) {
                this.rows.forEach(item2 => {
                  // eslint-disable-next-line eqeqeq
                  if (item2.id == item.itemId) {
                    console.log(item2.id + '---' + item.itemId)
                    console.log('item2----', item2)
                    console.log('item----', item)
                    item2.finelineNbr = JSON.parse(JSON.stringify(item.finelineNbr))
                    this.rowsApproval.push(item2)
                  }
                })
              }
            })
          }
        }, error => {
          console.log(error)
          this.loading = false
        })
        console.log(this.rowsApproval)
        console.log(this.rowsApproval.length)
        if (this.rowsApproval.length < 1) {
          this.batchAgree()
        } else {
          this.agreeCoi()
        }
        console.log('window.coiFlag:' + window.coiFlag)
      } else {
        console.log('window.coiFlag:' + window.coiFlag)
        this.batchAgree()
      }
    },
    // 批量同意触发
    agreeCoi() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要审核的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        const _this = this.$refs.choice
        _this.gridData = []
        _this.dialogTableVisible = true
        _this.gridData = JSON.parse(JSON.stringify(this.rowsApproval))
        _this.ids = this.ids
        _this.idsApproval = this.idsApproval
        // 是否批量提交
        _this.batchFlag = true
      }
    },
    // 批量同意触发
    batchAgreeCoi() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要审核的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.loading = true
        batchFirstAuditAgree(this.ids).then(res => {
          this.toQuery()
          Message({
            message: '审核完成。',
            type: 'success',
            duration: 3 * 1000
          })
          this.loading = false
        }, error => {
          console.log(error)
          this.loading = false
        })
      }
    },
    // 批量同意触发
    batchAgree() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要审核的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$confirm('确认审核通过选择的 ' + this.ids.length + ' 条item信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          batchFirstAuditAgree(this.ids).then(res => {
            this.toQuery()
            Message({
              message: '审核完成。',
              type: 'success',
              duration: 3 * 1000
            })
            this.loading = false
          }, error => {
            console.log(error)
            this.loading = false
          })
        })
      }
    },
    // 批量审核驳回
    batchReject() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要审核的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$prompt('请输入驳回原因', '驳回 ' + this.ids.length + ' 条Item', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: this.rejectRemarkValidator,
          type: 'warning'
        }).then((rejectRemark) => {
          this.loading = true
          batchFirstAuditReject(this.ids, rejectRemark.value).then(res => {
            this.toQuery()
            Message({
              message: '审核完成。',
              type: 'success',
              duration: 3 * 1000
            })
            this.loading = false
          }, error => {
            console.log(error)
            this.loading = false
          })
        })
      }
    },
    rejectRemarkValidator(val) {
      if (!val) {
        return '请填写驳回原因'
      } else if (val.length > 500) {
        return '驳回原因长度为1-500'
      }
      return true
    },
    // 批量转交Item
    doBatchChangeBuyer() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要转交的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$prompt('请输入需转交处理人的User ID', '转交 ' + this.ids.length + ' 条Item', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((changeBuyerId) => {
          this.loading = true
          batchChangeBuyer(this.ids, changeBuyerId.value).then(res => {
            this.toQuery()
            Message({
              message: '转交成功。',
              type: 'success',
              duration: 3 * 1000
            })
            this.loading = false
          }, error => {
            console.log(error)
            this.loading = false
          })
        })
      }
    },
    // 清空选择项
    doClearSelection() {
      this.$refs.itemTab.clearSelection()
    },
    // 批量导出
    doExportExcel() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要导出的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$confirm('确认导出选择的 ' + this.ids.length + ' 条item信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          doDownload('/new-item/exportExcel', { ids: this.ids }, 'new-item.xlsx').then(() => {
            this.loading = false
          }, error => {
            console.log(error)
            this.loading = false
          })
        })
      }
    }
  }
}
</script>
